package com.huaxindata.im.main.chat.Helper;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.huaxindata.im.R;
import com.huaxindata.im.main.chat.ConversationManager;
import com.huaxindata.im.main.chat.adapter.ChatAdapter;
import com.huaxindata.im.main.chat.listener.VoicePlayClickListener;
import com.huaxindata.im.main.chat.mp3recorder.EncodeCallback;
import com.huaxindata.im.main.chat.mp3recorder.MP3Recorder;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.util.FileUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;

/**
 * 主要是发送语音按扭的一个触摸监听
 * 在这里面实现录语音文件的功能
 */
public class VoiceHelper {
    /**
     * 按住说话listener
     */
    public static class PressToSpeakListen implements View.OnTouchListener {

        MP3Recorder                         mp3Recorder;
        File                                recordFile;
        Activity                            context;
        View                                recordingContainer;//屏幕上弹出来的录音的提示和动画的view
        TextView                            recordingHint;
        ChatAdapter                         adapter;
        Contact                             toChat;
        LinkedHashMap<Integer, ChatMessage> sendBuffer;
        MicHandler                          micImageHandler;

        public PressToSpeakListen(Activity context, View recordingContainer, TextView recordingHint
                , ImageView micImage, ChatAdapter adapter) {
            this.context = context;
            this.recordingContainer = recordingContainer;
            this.recordingHint = recordingHint;
            this.adapter = adapter;
            micImageHandler = new VoiceHelper.MicHandler();
            micImageHandler.setWeakReference(micImage);
        }

        public void release() {
            context = null;
            recordingContainer = null;
            recordingHint = null;
            adapter = null;
            toChat = null;
            sendBuffer = null;
            micImageHandler = null;
        }

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    try {
                        v.setPressed(true);
                        if (VoicePlayClickListener.isPlaying)
                            VoicePlayClickListener.currentPlayListener.stopPlayVoice();
                        recordingContainer.setVisibility(View.VISIBLE);
                        recordingHint.setText(context.getString(R.string.move_up_to_cancel));
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);
                        if (mp3Recorder != null && mp3Recorder.isRecording()) {
                            mp3Recorder.stop(null);
                        }
                        String file=FileUtil.getChatFileCacheDir(context, ConversationManager.getChatObject().getClientId());
                        File voiceDir = new File(file);
                        if (!voiceDir.exists()) {
                            voiceDir.mkdirs();
                        }
                        recordFile = new File(voiceDir,"audio_"+System.currentTimeMillis()+".mp3");
                        if (!recordFile.exists()) {
                            recordFile.createNewFile();
                        }
                        mp3Recorder = new MP3Recorder(recordFile, micImageHandler);
                        mp3Recorder.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                        v.setPressed(false);
                        if (mp3Recorder != null)
                            mp3Recorder.stop(null);
                        if (recordFile != null && recordFile.exists()) {
                            if (!recordFile.delete()) {
                                Log.d("xxx","delete tmp file failed!");
                            }
                        }
                        mp3Recorder = null;
                        recordFile = null;
                        recordingContainer.setVisibility(View.INVISIBLE);
                        Toast.makeText(context,"录音失败，请偿试",Toast.LENGTH_SHORT).show();
                        return false;
                    }

                    return true;
                case MotionEvent.ACTION_MOVE: {
                    if (event.getY() < 0) {
                        recordingHint.setText(context.getString(R.string.release_to_cancel));
                        recordingHint.setBackgroundResource(R.drawable.recording_text_hint_bg);
                    } else {
                        recordingHint.setText(context.getString(R.string.move_up_to_cancel));
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);
                    }
                    return true;
                }
                case MotionEvent.ACTION_UP:
                    v.setPressed(false);
                    recordingContainer.setVisibility(View.INVISIBLE);
                    if (event.getY() < 0) {
                        // discard the recorded audio.
                        mp3Recorder.stop(null);

                    } else {
                        // stop recording and send voice file
                        /**
                         * MP3编码器停止后，需要将缓存里的数据flush到文件，同步考虑，这里采用了回调机制
                         */
                        final int validBufferSize = mp3Recorder.getBufferSize();
                        mp3Recorder.stop(new EncodeCallback() {
                            @Override
                            public void flushFinish() {
                                try {
                                    if (recordFile.exists()) {
                                        if (recordFile.length() > validBufferSize) {
                                            FileHelper.sendVoiceMessage(context,recordFile,adapter);
                                        } else {
                                            Toast.makeText(context,"录音时间太短",Toast.LENGTH_SHORT).show();
                                        }
                                    } else {
                                        Toast.makeText(context,"无录音权限",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Toast.makeText(context,"发送失败，请检测服务器是否连接",Toast.LENGTH_SHORT).show();
                                }
                                mp3Recorder = null;
                            }
                        });
                    }
                    return true;
                default:
                    recordingContainer.setVisibility(View.INVISIBLE);
                    if (mp3Recorder != null)
                        mp3Recorder.stop(null);
                    if (recordFile != null && recordFile.exists()) {
                        if (!recordFile.delete()) {
                            Log.d("xxx","delete tmp file failed!");
                        }
                    }
                    mp3Recorder = null;
                    return false;
            }
        }
    }

    /**
     * 主要用于子线程和主线程通信，主线程更新Ui
     */
    public static class MicHandler extends Handler {

        public WeakReference<ImageView> weakReference;

        public void setWeakReference(ImageView tag) {
            this.weakReference = new WeakReference<>(tag);
        }
        @Override
        public void handleMessage(android.os.Message msg) {
            // 切换msg切换图片
            if (weakReference.get() != null) {
                switch (msg.what) {
                    case 0:
                        weakReference.get().setImageResource(R.mipmap.record_animate_01);
                        break;
                    case 1:
                        weakReference.get().setImageResource(R.mipmap.record_animate_02);
                        break;
                    case 2:
                        weakReference.get().setImageResource(R.mipmap.record_animate_03);
                        break;
                    case 3:
                        weakReference.get().setImageResource(R.mipmap.record_animate_04);
                        break;
                    case 4:
                        weakReference.get().setImageResource(R.mipmap.record_animate_05);
                        break;
                    case 5:
                        weakReference.get().setImageResource(R.mipmap.record_animate_06);
                        break;
                    case 6:
                        weakReference.get().setImageResource(R.mipmap.record_animate_07);
                        break;
                    case 7:
                        weakReference.get().setImageResource(R.mipmap.record_animate_08);
                        break;
                    case 8:
                        weakReference.get().setImageResource(R.mipmap.record_animate_09);
                        break;
                    case 9:
                        weakReference.get().setImageResource(R.mipmap.record_animate_10);
                        break;
                    case 10:
                        weakReference.get().setImageResource(R.mipmap.record_animate_11);
                        break;
                    case 11:
                        weakReference.get().setImageResource(R.mipmap.record_animate_12);
                        break;
                    case 12:
                        weakReference.get().setImageResource(R.mipmap.record_animate_13);
                        break;
                    default:
                        weakReference.get().setImageResource(R.mipmap.record_animate_14);
                        break;
                }
            }
        }
    }
}
